import { useEffect, useState } from 'react';
import * as echarts from 'echarts';
import 'echarts/lib/chart/boxplot';
import emitter from '#/utils/events';
import { DragLine } from './utils';
import renovate from '#/utils/renovate';

function useECharts({
  chartRef,
  config,
  getPointPosition,
  coordRange,
  coord,
  type = 'column',
  minusHeight = 0,
  initHeight = 0,
  dragLineId = '',
  dragChangeList,
}) {
  let chartInstance = null;
  const [height, setHeight] = useState(
    type === 'column' ? 600 : document.body.clientHeight - minusHeight,
  );
  function renderChart() {
    const renderedInstance = echarts.getInstanceByDom(chartRef.current);
    if (renderedInstance) {
      chartInstance = renderedInstance;
    } else {
      chartInstance = echarts.init(chartRef.current);
    }
    coord ? chartInstance.setOption(config) : chartInstance.setOption(config, true);
    chartInstance.resize();
  }

  useEffect(() => {
    try {
      renderChart();
    } catch (error) {
      // console.log(error);
    }
  }, [config]);

  useEffect(() => {
    //通过选中table来初始化选中的点
    let timer = setTimeout(() => {
      //默认选中toolbox上lineX
      chartInstance &&
        chartInstance.dispatchAction({
          type: 'takeGlobalCursor',
          key: 'brush',
          brushOption: {
            brushType: 'lineX',
          },
        }),
        0;
    });
    chartInstance &&
      coord &&
      chartInstance.on('brushSelected', (params) => {
        const { batch } = params;
        if (batch && batch.length > 0) {
          if (batch[0].areas && batch[0].areas.length > 0) {
            const _coordRange = batch[0].areas;
            let data = _coordRange.map((item) => item.coordRange);
            getPointPosition && getPointPosition(data);
          } else {
            getPointPosition && getPointPosition([]);
          }
        }
      });
    return () => {
      clearTimeout(timer);
    };
  }, []);

  useEffect(() => {
    chartInstance &&
      coord &&
      chartInstance.dispatchAction({
        type: 'brush',
        areas: coordRange.map((item) => ({
          brushType: 'lineX',
          coordRange: item,
          xAxisIndex: 0,
        })),
      });
  }, [coordRange]);

  useEffect(() => {
    if (!String(dragLineId).length || !chartInstance || !config.series.length) return;
    let filterData = config.series.filter((item) => item.id === dragLineId);
    let data = [];
    // if (tableList[dragLineId].list.some(item => item.isLock)) {
    //   tableList[dragLineId].list.map(item => {
    //     if (item.xAxis && !item.isLock) {
    //       data.push(item.value);
    //     }
    //   });
    // } else {
    data = filterData[0]?.list.map((item) => item.value);
    // }
    DragLine(
      chartInstance,
      dragLineId,
      data,
      () => {
        try {
          chartInstance.setOption({
            graphic: echarts.util.map(data, function (item, dataIndex) {
              return {
                position: chartInstance.convertToPixel({ seriesIndex: 0 }, [dataIndex, item]),
              };
            }),
          });
        } catch (err) {
          // err
        }
      },
      renovate,
      () => {
        dragChangeList(chartInstance);
      },
    );
    chartInstance.setOption(config, true);
  }, [dragLineId, chartInstance, config]);

  useEffect(() => {
    return () => {
      chartInstance && chartInstance.dispose();
    };
  }, []);

  useEffect(() => {
    emitter.addListener('onChangeMnue', _onHandleResize);
    window.addEventListener('resize', () => {
      if (!chartRef) {
        window.removeEventListener('resize', handleCartsResize);
        return;
      }
      let height =
        type === 'column'
          ? initHeight > 0
            ? initHeight
            : parseInt(parseInt(document.body.clientHeight) * 0.6)
          : parseInt(document.body.clientHeight - minusHeight);
      setHeight(height);
      handleCartsResize();
    });
    return () => {
      emitter.removeListener('onChangeMnue', _onHandleResize);
      window.removeEventListener('resize', handleCartsResize);
    };
  }, [config]);

  const _onHandleResize = () => {
    setTimeout(() => {
      handleCartsResize();
    }, 500);
  };
  const handleCartsResize = () => {
    chartInstance && chartInstance.resize();
  };

  const _chartInstance = () => {
    return chartInstance && chartInstance;
  };

  return { height, _chartInstance };
}

export default useECharts;
